import { useUserStoreHook } from "@/store/modules/user";

const navigator = window?.navigator || {};

/**
 * Check if an element has a class
 * @param {HTMLElement} ele
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele: HTMLElement, cls: string) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function addClass(ele: HTMLElement, cls: string) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function removeClass(ele: HTMLElement, cls: string) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
  const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
  return isExternal;
}
/**
 * @description 生成随机数
 * @param {Number} min 最小值
 * @param {Number} max 最大值
 * @returns {Number}
 */
export function randomNum(min: number, max: number): number {
  const num = Math.floor(Math.random() * (min - max) + max);
  return num;
}

/**
 * @description 获取当前时间对应的提示语
 * @returns {String}
 */
export function getTimeState() {
  const timeNow = new Date();
  const hours = timeNow.getHours();
  if (hours >= 6 && hours <= 10) return `早上好 ⛅`;
  if (hours >= 10 && hours <= 14) return `中午好 🌞`;
  if (hours >= 14 && hours <= 18) return `下午好 🌞`;
  if (hours >= 18 && hours <= 24) return `晚上好 🌛`;
  if (hours >= 0 && hours <= 6) return `凌晨好 🌛`;
}

/**
 * @description:  是否为数组
 */
export function isArray(val: any): val is Array<any> {
  return val && Array.isArray(val);
}

/**
 * @description:  拼接路由链接地址 ?以后部分
 * encodeSearchParams({name:1})
 */
export function encodeSearchParams(obj: any) {
  const params: any[] = [];
  Object.keys(obj).forEach((key) => {
    let value = obj[key];
    // 如果值为undefined我们将其置空
    if (typeof value === "undefined") {
      value = "";
    }
    // 对于需要编码的文本（比如说中文）我们要进行编码
    params.push([key, encodeURIComponent(value)].join("="));
  });

  return params.join("&");
}

/**
 * @description:  获取操作系统类型
 * getOSInfo()
 */

// 获取操作系统
function getUserOsInfo() {
  const navigator = window?.navigator || {};
  const userAgent = navigator?.userAgent || "";
  if (userAgent.indexOf("Windows NT 10.0") !== -1) return "Windows 10";
  if (userAgent.indexOf("Windows NT 6.2") !== -1) return "Windows 8";
  if (userAgent.indexOf("Windows NT 6.1") !== -1) return "Windows 7";
  if (userAgent.indexOf("Windows NT 6.0") !== -1) return "Windows Vista";
  if (userAgent.indexOf("Windows NT 5.1") !== -1) return "Windows XP";
  if (userAgent.indexOf("Windows NT 5.0") !== -1) return "Windows 2000";
  if (userAgent.indexOf("Mac") !== -1) return "Mac/iOS";
  if (userAgent.indexOf("X11") !== -1) return "UNIX";
  if (userAgent.indexOf("Linux") !== -1) return "Linux";
  return "Other";
}
export async function getOSInfo() {
  const operatingSystem = getUserOsInfo(); // 返回操作系统
  if (operatingSystem === "Windows 10") {
    const os = await navigator?.userAgentData
      .getHighEntropyValues(["platformVersion"])
      .then((ua: any) => {
        if (navigator?.userAgentData.platform === "Windows") {
          const majorPlatformVersion = parseInt(
            ua.platformVersion.split(".")[0]
          );
          if (majorPlatformVersion >= 13) {
            return "Windows 11";
          } else {
            return operatingSystem;
          }
        } else {
          // console.log("Not running on Windows")
          return operatingSystem;
        }
      });
    console.log("os", os);
    return os;
  } else {
    console.log("operatingSystem", operatingSystem);
    return operatingSystem;
  }
}

export function isWindow7() {
  // return getUserOsInfo() === "Windows 7" || document.body.clientWidth < 1050;
  // return document.body.clientWidth < 1050;
  return false;
}

/**
 * @description 格式化表格单元格默认值 (el-table-column)
 * @param {Number} row 行
 * @param {Number} col 列
 * @param {*} callValue 当前单元格值
 * @returns {String}
 * */
export function formatTableColumn(row: number, col: number, callValue: any) {
  // 如果当前值为数组，使用 / 拼接（根据需求自定义）
  if (isArray(callValue)) return callValue.length ? callValue.join(" / ") : "";
  return callValue ?? "";
}

/**
 * @description 处理 ProTable 值为数组 || 无数据
 * @param {*} callValue 需要处理的值
 * @returns {String}
 * */
export function formatValue(callValue: any) {
  // 如果当前值为数组，使用 / 拼接（根据需求自定义）
  if (isArray(callValue)) return callValue.length ? callValue.join(" / ") : "";
  return callValue ?? "";
}

/**
 * @description 处理 prop 为多级嵌套的情况，返回的数据 (列如: prop: user.name)
 * @param {Object} row 当前行数据
 * @param {String} prop 当前 prop
 * @returns {*}
 * */
export function handleRowAccordingToProp(
  row: { [key: string]: any },
  prop: string
) {
  if (!prop.includes(".")) return row[prop] ?? "";
  prop.split(".").forEach((item) => (row = row[item] ?? ""));
  return row;
}

/**
 * @description 处理 prop，当 prop 为多级嵌套时 ==> 返回最后一级 prop
 * @param {String} prop 当前 prop
 * @returns {String}
 * */
export function handleProp(prop: string) {
  const propArr = prop.split(".");
  if (propArr.length == 1) return prop;
  return propArr[propArr.length - 1];
}

/**
 * @description 根据枚举列表查询当需要的数据（如果指定了 label 和 value 的 key值，会自动识别格式化）
 * @param {String} callValue 当前单元格值
 * @param {Array} enumData 字典列表
 * @param {Array} fieldNames label && value && children 的 key 值
 * @param {String} type 过滤类型（目前只有 tag）
 * @returns {String}
 * */
export function filterEnum(
  callValue: any,
  enumData?: any,
  fieldNames?: any,
  type?: "tag"
) {
  const value = fieldNames?.value ?? "value";
  const label = fieldNames?.label ?? "label";
  const children = fieldNames?.children ?? "children";
  let filterData: { [key: string]: any } = {};
  // 判断 enumData 是否为数组
  if (Array.isArray(enumData))
    filterData = findItemNested(enumData, callValue, value, children);
  // 判断是否输出的结果为 tag 类型
  if (type == "tag") {
    return filterData?.tagType ? filterData.tagType : "";
  } else {
    return filterData ? filterData[label] : "";
  }
}

/**
 * @description 递归查找 callValue 对应的 enum 值
 * */
export function findItemNested(
  enumData: any,
  callValue: any,
  value: string,
  children: string
) {
  return enumData.reduce((accumulator: any, current: any) => {
    if (accumulator) return accumulator;
    if (current[value] === callValue) return current;
    if (current[children])
      return findItemNested(current[children], callValue, value, children);
  }, null);
}
/**
 * @description 工作台页面url拼接
 * */
export function filterDemoTemplateUrl(url: string, type?: string) {
  let result = "";
  if (type) {
    const componentArray = url?.split("/");
    componentArray.splice(-1, 0, "Demo");
    const lastValue = "Demo" + componentArray[componentArray.length - 1];
    componentArray[componentArray.length - 1] = lastValue;
    result = componentArray.join("/");
  } else {
    result = url;
  }
  return result || "";
}
/**
 * @description 获取工作台名称
 * */
export function filterDemoTemplateName(url: string) {
  let result = "";
  const componentArray = url?.split("/");
  result = componentArray[componentArray.length - 1];
  return result || "";
}

/**
 * @description 是否是暗黑模式页面
 * */
const routeNameList = [
  "WORKBENCHTEAMWORKBENCH",
  "ProduceDataMonitorView",
  "ProduceLineMonitorView",
  "DATASCREENMES",
  "DATASCREENJTSCREENCUSTOMIZE",
  "DATASCREENJTSCREENCUSTOMIZEEAM",
  "DATASCREENJTCUSTOMIZESCREEN"
];
export function isDarkMode(name: any) {
  let isDark = false;
  if (routeNameList.indexOf(name) !== -1) {
    isDark = true;
  }
  return isDark;
}

/**
 * @description 获取随机数
 * */
export function getRandomNumber(min: number, max: number) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

/**
 * @description just helper to get current dates
 * */
export function getDate(hours: number) {
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear();
  const currentMonth = currentDate.getMonth();
  const currentDay = currentDate.getDate();
  const timeStamp = new Date(
    currentYear,
    currentMonth,
    currentDay,
    0,
    0,
    0
  ).getTime();
  return new Date(timeStamp + hours * 60 * 60 * 1000).getTime();
}

/**
 * 是否存在权限
 * @param {string[]} permsArray 权限数组
 * @returns {boolean}
 *
 * authAllPerm(['sys:org:menu:operate:add','sys:org:menu:operate:edit','sys:org:menu:del'])
 * 如果用户权限中不包含所有传递过来的权限数组，则返回false，否则返回true
 */
export const authAllPerm: Function = (permsArray: string[]) => {
  const { perms } = useUserStoreHook().user;
  if (perms.length === 0) {
    return false;
  } else {
    const hasPerm = permsArray?.some((perm) => {
      return perms.includes(perm);
    });
    return hasPerm;
  }
};

export function keyWorkEditPerm(task: any) {
  const { userId, userType } = useUserStoreHook().user;
  return (
    task.createdUserId === userId ||
    userType === "superadmin" ||
    task.leaderId === userId
  );
}
